package com.example.userservice.controller;

import com.example.userservice.client.CourseClient;
import com.example.userservice.client.EnrollClient;
import com.example.userservice.entity.user_account;
import com.example.userservice.entity.UserRole;
import com.example.userservice.service.UserService;
import com.example.userservice.service.UserRoleService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private UserService userService;
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Autowired
    private CourseClient courseClient;
    
    @Autowired
    private EnrollClient enrollClient;

    // 管理员主页
//    @GetMapping("/home")
//    public String adminHome(HttpSession session, Model model) {
//        System.out.println("进入管理员主页");
//        user_account user = (user_account) session.getAttribute("user");
//        if (user == null) {
//            return "redirect:/login";
//        }
//        model.addAttribute("user", user);
//        return "HomeAdmin";
//    }

    // 添加新用户
    @PostMapping("/users/add")
    @ResponseBody
    public String addUser(@RequestBody Map<String, Object> userData) {
        try {
            String username = (String) userData.get("username");
            String email = (String) userData.get("email");
            String password = (String) userData.get("password");
            Integer roleId = (Integer) userData.get("roleId");
            
            if (username == null || username.trim().isEmpty()) {
                return "用户名不能为空";
            }
            if (email == null || email.trim().isEmpty()) {
                return "邮箱不能为空";
            }
            if (password == null || password.trim().isEmpty()) {
                return "密码不能为空";
            }
            if (roleId == null || roleId == 1) {
                return "角色不能为空且不能是管理员";
            }
            
            // 检查用户名是否已存在
            user_account existingUser = userService.lambdaQuery()
                    .eq(user_account::getUsername, username)
                    .one();
            if (existingUser != null) {
                return "用户名已存在";
            }
            
            // 检查邮箱是否已存在
            existingUser = userService.lambdaQuery()
                    .eq(user_account::getEmail, email)
                    .one();
            if (existingUser != null) {
                return "邮箱已存在";
            }
            
            // 创建新用户
            user_account newUser = new user_account();
            newUser.setUsername(username.trim());
            newUser.setEmail(email.trim());
            newUser.setPassword(password.trim());
            newUser.setStatus(1); // 默认启用
            
            userService.save(newUser);
            
            // 添加用户角色
            UserRole userRole = new UserRole();
            userRole.setUserId(newUser.getId());
            userRole.setRoleId(roleId);
            userRoleService.save(userRole);
            
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "添加用户失败: " + e.getMessage();
        }
    }

    // 获取所有非管理员用户
    @GetMapping("/users")
    @ResponseBody
    public List<Map<String, Object>> getAllUsers() {
        try {
            // 查询非管理员用户（role_id != 3）
            return userService.getNonAdminUsers();
        } catch (Exception e) {
            e.printStackTrace();
            return List.of();
        }
    }

    // 获取用户详情
    @GetMapping("/users/{userId}")
    @ResponseBody
    public user_account getUserDetail(@PathVariable Long userId) {
        return userService.getById(userId);
    }

    // 更新用户信息
    @PostMapping("/users/{userId}/update")
    @ResponseBody
    public String updateUser(@PathVariable Long userId, @RequestBody Map<String, Object> userData) {
        try {
            user_account user = userService.getById(userId);
            if (user == null) {
                return "用户不存在";
            }

            // 检查用户是否为管理员（通过user_role表查询）
            // 这里需要查询user_role表来确认用户角色
            // 暂时简化处理，实际项目中需要完善角色检查逻辑
            
            // 更新用户信息
            if (userData.containsKey("username")) {
                user.setUsername((String) userData.get("username"));
            }
            if (userData.containsKey("email")) {
                user.setEmail((String) userData.get("email"));
            }
            if (userData.containsKey("status")) {
                user.setStatus((Integer) userData.get("status"));
            }

            userService.updateById(user);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "更新失败: " + e.getMessage();
        }
    }

    // 删除用户
    @DeleteMapping("/users/{userId}")
    @ResponseBody
    public String deleteUser(@PathVariable Long userId) {
        try {
            user_account user = userService.getById(userId);
            if (user == null) {
                return "用户不存在";
            }

            userService.removeById(userId);
            return "ok";
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败: " + e.getMessage();
        }
    }

    // 获取所有课程
    @GetMapping("/courses")
    @ResponseBody
    public List<Map<String, Object>> getAllCourses() {
        try {
            List<Map<String, Object>> courses = courseClient.listAllCourses();
            
            // 为每个课程添加学生数量和教师信息
            for (Map<String, Object> course : courses) {
                Integer courseId = (Integer) course.get("id");
                
                // 获取学生数量（已批准的选课）
                try {
                    List<Map<String, Object>> enrollments = enrollClient.getCourseEnrollments(courseId);
                    long studentCount = enrollments.stream()
                            .filter(enrollment -> (Integer) enrollment.get("status") == 1) // 1=APPROVED
                            .count();
                    course.put("studentCount", studentCount);
                } catch (Exception e) {
                    course.put("studentCount", 0);
                }
                
                // 获取教师信息
                Integer createdBy = (Integer) course.get("createdBy");
                if (createdBy != null) {
                    try {
                        user_account teacher = userService.getById(createdBy.longValue());
                        if (teacher != null) {
                            course.put("teacherName", teacher.getUsername());
                        } else {
                            course.put("teacherName", "未知");
                        }
                    } catch (Exception e) {
                        course.put("teacherName", "未知");
                    }
                } else {
                    course.put("teacherName", "未知");
                }
            }
            
            return courses;
        } catch (Exception e) {
            e.printStackTrace();
            return List.of();
        }
    }

    // 获取课程详情
    @GetMapping("/courses/{courseId}")
    @ResponseBody
    public Map<String, Object> getCourseDetail(@PathVariable int courseId) {
        try {
            List<Map<String, Object>> courses = courseClient.listAllCourses();
            return courses.stream()
                    .filter(course -> (Integer) course.get("id") == courseId)
                    .findFirst()
                    .orElse(new HashMap<>());
        } catch (Exception e) {
            e.printStackTrace();
            return new HashMap<>();
        }
    }


    // 更新课程信息
    @PostMapping("/courses/{courseId}/update")
    @ResponseBody
    public String updateCourse(@PathVariable int courseId, @RequestBody Map<String, Object> courseData) {
        try {
            return courseClient.adminUpdateCourse(courseId, courseData);
        } catch (Exception e) {
            e.printStackTrace();
            return "更新失败: " + e.getMessage();
        }
    }

    // 删除课程
    @DeleteMapping("/courses/{courseId}")
    @ResponseBody
    public String deleteCourse(@PathVariable int courseId) {
        try {
            return courseClient.adminDeleteCourse(courseId);
        } catch (Exception e) {
            e.printStackTrace();
            return "删除失败: " + e.getMessage();
        }
    }

    // 批量删除课程
    @PostMapping("/courses/batch-delete")
    @ResponseBody
    public String batchDeleteCourses(@RequestBody List<Integer> courseIds) {
        try {
            if (courseIds == null || courseIds.isEmpty()) {
                return "请选择要删除的课程";
            }
            
            int successCount = 0;
            int failCount = 0;
            StringBuilder errorMessages = new StringBuilder();
            
            for (Integer courseId : courseIds) {
                try {
                    String result = courseClient.adminDeleteCourse(courseId);
                    if ("ok".equals(result)) {
                        successCount++;
                    } else {
                        failCount++;
                        errorMessages.append("课程ID ").append(courseId).append(": ").append(result).append("; ");
                    }
                } catch (Exception e) {
                    failCount++;
                    errorMessages.append("课程ID ").append(courseId).append(": ").append(e.getMessage()).append("; ");
                }
            }
            
            if (failCount == 0) {
                return "ok";
            } else {
                return "成功删除 " + successCount + " 个课程，失败 " + failCount + " 个。错误信息: " + errorMessages.toString();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "批量删除失败: " + e.getMessage();
        }
    }

    // 更新课程状态
    @PostMapping("/courses/{courseId}/status")
    @ResponseBody
    public String updateCourseStatus(@PathVariable int courseId, @RequestBody Map<String, Object> statusData) {
        try {
            Integer status = (Integer) statusData.get("status");
            if (status == null) {
                return "状态不能为空";
            }
            
            Map<String, Object> updateData = new HashMap<>();
            updateData.put("status", status);
            
            return courseClient.adminUpdateCourse(courseId, updateData);
        } catch (Exception e) {
            e.printStackTrace();
            return "更新状态失败: " + e.getMessage();
        }
    }

    // 获取系统统计信息
    @GetMapping("/statistics")
    @ResponseBody
    public Map<String, Object> getStatistics() {
        Map<String, Object> stats = new HashMap<>();
        try {
            // 用户统计
            long totalUsers = userService.count();
            stats.put("totalUsers", totalUsers);

            // 课程统计
            List<Map<String, Object>> courses = courseClient.listAllCourses();
            stats.put("totalCourses", courses.size());

            // 其他统计信息
            stats.put("activeUsers", totalUsers * 0.8); // 假设80%用户活跃
            stats.put("courseCompletionRate", 0.86); // 假设86%课程完成率

            return stats;
        } catch (Exception e) {
            e.printStackTrace();
            stats.put("error", "获取统计信息失败");
            return stats;
        }
    }
}
